package routers

import (
	"awesome/models"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func InitGroup() {

	Api.GET("/groups", func(c *gin.Context) {
		var groups *[]models.Group
		page := c.DefaultQuery("page", "0")
		pageInt, err := strconv.Atoi(page)
		if err != nil {
			pageInt = 0
		}
		size := c.DefaultQuery("size", "10")
		sizeInt, err := strconv.Atoi(size)
		if err != nil {
			pageInt = 0
		}
		offset := pageInt * sizeInt

		groups, _ = models.GetGroupList(sizeInt, offset)
		c.JSONP(http.StatusOK, groups)
	})

	Api.GET("/group/:id", func(c *gin.Context) {
		id := c.Param("id")
		var user *models.Group
		var idu, err = strconv.ParseUint(id, 10, 64)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid ID"})
			return
		}
		user, _ = models.GetGroupByID(uint(idu))
		c.JSONP(http.StatusOK, user)
	})

	Api.POST("/group", func(c *gin.Context) {
		var group *models.Group
		err := c.BindJSON(&group)
		if err != nil {
			c.JSONP(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		println(group)
		err = models.CreateGroup(group)
		if err != nil {
			return
		}
		c.JSONP(http.StatusOK, group)
	})
}
